/*
MIT License

Copyright (c) 2022 МГТУ им. Н.Э. Баумана, кафедра ИУ-6, Михаил Фетисов,

https://bmstu.codes/lsx/simodo/loom
*/

#include "simodo/variable/Variable.h"
#include "simodo/bormental/DrBormental.h"

#include "simodo/inout/convert/functions.h"

#include <cassert>

namespace simodo::variable
{
    const std::shared_ptr<Object> Specification::getObjectPtr() const
    {
        if (!isObject()) {
            assert(isNull());
            const_cast<Specification *>(this)->setValue(std::make_shared<Object>());
        }

        assert(isObject());
        return getObject();
    }

    const Value & Specification::find(const std::u16string & spec_name) const
    {
        static const Value null = {};

        if (!isObject())
            return null;

        auto it = std::find_if(object()->variables().begin(), object()->variables().end(),
                [spec_name](const Variable & v){
                    return v.name() == spec_name;
                });

        if (it == object()->variables().end())
            return null;

        return it->value();
    }

    void Specification::set(const std::u16string & name, const Value & value)
    {
        auto it = std::find_if(object()->variables().begin(), object()->variables().end(),
                [name](const Variable & v){
                    return v.name() == name;
                });

        if (it == object()->variables().end())
            object()->variables().push_back(Variable{name, value});
        else 
            it->value() = value;
    }

}